<template>
  <div class="tea-upload">
    <div>
      <div style="height: 0; overflow: hidden">
        <el-image
          style="width: 100px; height: 100px"
          :src="allList[0] | getPath(host)"
          :preview-src-list="[dialogImageUrl]"
          ref="preview"
        >
        </el-image>
      </div>
      <ul class="tea-upload-list">
        <li
          class="tea-upload-item"
          v-for="(item, index) in allList"
          :key="index"
        >
          <div
            class="tea-upload-item-body"
            @mouseover="hoverIndex = index"
            @mouseout="hoverIndex = ''"
          >
            <img
              class="tea-upload-item-img"
              :src="item.url | getRealPath(item.path, host)"
              alt=""
            />
            <div class="upload-options" v-show="hoverIndex === index">
              <div class="upload-options-body">
                <div class="el-icon-zoom-in" @click="preview(item)"></div>
                <div class="el-icon-delete" @click="remove(item)"></div>
              </div>
            </div>
          </div>
        </li>
      </ul>
      <div class="tea-upload-input" @click.stop="getUpload">
        <i class="el-icon-plus"></i>
      </div>
    </div>
    <input
      class="tea-upload-realinput"
      type="file"
      ref="tea-upload"
      :multiple="multiple"
      @change="uploadFile"
    />
  </div>
</template>

<script>
import { uploadBackImg, deleteBackImg } from "@/api/tea-manager";
import { mapState } from "vuex";
export default {
  name: "TeaUpload",
  filters: {
    getPath(item, host) {
      try {
        const { url, path } = item;
        if (url) {
          return url;
        }
        return host + path;
      } catch (e) {
        // console.log(e);
      }
      return "/logo.png";
    },
    getRealPath(url, path, host) {
      if (url) {
        return url;
      }
      return host + path;
    },
  },
  props: {
    multiple: {
      type: Boolean,
      default: true,
    },

    keyId: {
      type: Number,
      default: 0,
    },
    imgType: {
      type: Number,
      default: 0,
    },
    editList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      uploadList: [],
      selectList: [],
      num: 0,
      hoverIndex: "",
      dialogImageUrl: "",
    };
  },
  created() {
    console.log("执行了");
    console.log(this.ids);
  },
  computed: {
    ...mapState({
      host: (state) => state.url,
    }),
    allList() {
      return [...this.editList, ...this.uploadList];
    },
  },
  methods: {
    remove(item) {
      const { id } = item;
      const { uploadList } = this;
      deleteBackImg(id)
        .then((res) => {
          if (res.data.code !== 200) {
            this.$message.error("删除失败");
            return;
          }
          this.uploadList = uploadList.filter(
            (fiterItem) => fiterItem.id !== id
          );
          this.$emit(
            "update:editList",
            this.editList.filter((fiterItem) => fiterItem.id !== id)
          );
          this.$message.success("删除成功");
        })
        .catch((err) => {
          this.$message.error("删除失败");
        });
    },
    preview(item) {
      if (item.url) {
        this.dialogImageUrl = item.url;
      }
      if (item.path) {
        this.dialogImageUrl = this.host + item.path;
      }
      this.$refs.preview.$el.getElementsByTagName("img")[0].click();
    },
    getUpload() {
      console.log(this.$refs["tea-upload"]);
      this.num += 1;
      this.$refs["tea-upload"].click();
    },
    uploadFile(e) {
      // view 是获取缓存对象 success是上传成功 fail是失败
      console.log(e);
      this.selectList = [...e.target.files].map((item) => {
        item.url = window.URL.createObjectURL(item); //创建blob地址，不然图片怎么展示？
        item.status = "view";
        item.uid = item.lastModified;
        return item;
      });
      console.log(this.selectList);
      this.realUploadFile();
    },
    async realUploadFile() {
      const { selectList } = this;
      let _keyId = 0;
      for (let i = 0; i < selectList.length; i++) {
        try {
          const data = new FormData();
          data.append("file", selectList[i]);
          const { keyId, imgType } = this;
          const params = { imgType };
          if (keyId) {
            params.keyId = keyId;
          } else if (_keyId) {
            params.keyId = _keyId;
          }
          console.log("this里面的keyId", keyId);
          console.log("作用域里的的keyId", _keyId);
          const res = await uploadBackImg({ data, params });
          if (res.data.code === 200) {
            !_keyId && (_keyId = res.data.data.otherKeyId);
            this.$emit("update:keyId", res.data.data.otherKeyId);
            selectList[i].id = res.data.data.id;
            selectList[i].realUrl = res.data.data.path;
            selectList[i].status = "success";
            selectList[i].imgType = res.data.data.imgType;
            selectList[i].imgType = res.data.data.otherKeyId;
            console.log(selectList[i]);

            this.uploadList.push(selectList[i]);
            this.$emit("on-success", selectList[i]);
          } else {
            this.$emit("on-error", res);
          }
          // 等待生效
          // await this.wait();
        } catch (err) {
          console.log(err);
          this.$emit("on-error", err);
        }
      }
      this.$emit("on-all-success", this.selectList);
    },
    wait(time = 500) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, time);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.tea-upload {
  .upload-options {
    // display: none;
    position: absolute;
    top: 50%;
    left: 50%;
    font-size: 22px;
    color: #fff;
    transform: translate(-50%, -50%);
    .upload-options-body {
      width: 148px;
      height: 148px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(0, 0, 0, 0.5);
      .el-icon-delete {
        margin-left: 15px;
      }
    }
  }
  .tea-upload-list {
    display: inline;
    vertical-align: top;
    margin: 0;
    padding: 0;
    list-style: none;
  }
  .tea-upload-item {
    cursor: pointer;
    overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    margin: 0 8px 8px 0;
    display: inline-block;
    transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
    font-size: 14px;
    color: #606266;
    line-height: 1.8;
    position: relative;
    list-style: none;
    .tea-upload-item-body {
      width: 100%;
      height: 100%;
    }
    .tea-upload-item-img {
      width: 100%;
      height: 100%;
    }
  }
  .tea-upload-input {
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    cursor: pointer;
    line-height: 148px;
    vertical-align: top;
    display: inline-block;
    text-align: center;
    outline: none;
    &:hover {
      border: 1px dashed #409eff;
    }
    i {
      font-size: 28px;
      color: #8c939d;
    }
  }
  .tea-upload-realinput {
    display: none;
    cursor: pointer;
  }
}
</style>
